﻿using System;
using System.Linq;
using System.Linq.Dynamic;

namespace iHouse.Infrastructure
{
    public class JqGridList<T> : IPagedList
    {
        public JqGridList()
        { }

        public JqGridList(IQueryable<T> source, int pageIndex, int pageSize, string sidx, string sord, string search, params object[] values)
        {
            if (pageIndex < 0)
                throw new ArgumentOutOfRangeException("index", pageIndex, "PageIndex cannot be below 0.");
            if (pageSize < 1)
                throw new ArgumentOutOfRangeException("pageSize", pageSize, "PageSize cannot be less than 1.");

            if (!string.IsNullOrEmpty(search))
            {
                source = source.Where(search, values);
            }

            PageSize = pageSize;
            PageIndex = pageIndex;
            TotalCount = source.Count();
            TotalPages = TotalCount > 0 ? (int)Math.Ceiling(TotalCount / (double)PageSize) : 0;

            if (!string.IsNullOrEmpty(sidx))
            {
                string order = string.Format("{0} {1}", sidx, sord);

                source = source.OrderBy(order);
            }

            Rows = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList().ToArray();
        }

        public T[] Rows
        {
            get;
            set;
        }

        public int TotalCount
        {
            get;
            set;
        }

        public int TotalPages
        {
            get;
            set;
        }

        public int PageIndex
        {
            get;
            set;
        }

        public int PageSize
        {
            get;
            set;
        }

        public dynamic UserData
        {
            get;
            set;
        }
    }
}